<?php
namespace Admin\Model;
use Think\Model;
/**
 * 规则模型
 */
class AuthRuleModel extends Model{
     //添加之前整理数据
    public function _before_insert(&$data, $options) {
        $status=I('post.status');
        if($status=='on'){
            $data['status']=1;
        }else{
            $data['status']=0;
        }
    }
    //修改之前整理数据
    public function _before_update(&$data, $options) {
        $status=I('post.status');
        if($status=='on'){
            $data['status']=1;
        }else{
            $data['status']=0;
        }
    }
    //获取树状结构的规则数据
    public function getTreeRule(){
        $data=  $this->select();
        return $this->_getTree($data);
    }
    //将获取出来的所有规则用递归的方式进行树状排序
    private function _getTree($data,$pid=0,$level=0){
        static $arr=array();
        foreach ($data as $key => $value) {
            if($value['pid']==$pid){
                $value['level']=$level;
                $arr[]=$value;
                $this->_getTree($data,$value['id'],$level+1);
            }
        }
        return $arr;
    }
    //删除规则之前判断该规则下是否有子规则，如果没有则删除，如果有则不允许删除
    public function _before_delete($options) {
        $id=I('get.id');
        $data=$this->select();
        return $this->_getChild($id,$data);
    }
    //根据当前规则id查询该规则下是否存在子规则
    private function _getChild($pid,$data){
        foreach ($data as $key => $value) {
            if($value['pid']==$pid){
                return false;
            }
        }
        return true;
    }
}

